/*
package com.yonyou.ucf.mdf.app.util;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.diwork.multilingual.model.LanguageVO;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.ucf.mdd.common.constant.MddConstants;
import com.yonyou.ucf.mdd.ext.core.AppContext;
import com.yonyou.ucf.mdd.ext.model.LoginUser;
import com.yonyou.ucf.mdd.ext.poi.constant.POIConstant;
import com.yonyou.ucf.mdf.app.service.impl.ISVAuthService;
import com.yonyoucloud.iuap.ucf.mdd.starter.core.module.data.cache.StringKeyCache;
import com.yonyoucloud.iuap.ucf.mdd.starter.core.module.data.cache.redis.UCFRedisCacheFactory;
import com.yonyoucloud.iuap.ucf.mdd.starter.token.service.TokenService;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.auth.CommonAuthApi;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.auth.pojo.CommonAuthResult;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.Cookie;
import java.time.Duration;
import java.util.Map;

*/
/**
 * @Author: LuoYu
 * @Date: 2021/6/4 16:29
 * @Description: 添加用户上下文
 *//*

@Slf4j
@Component
@RequiredArgsConstructor
public class ISVBuildContextUtil {

    protected final CommonAuthApi authApi;
    protected final TokenService tokenService;
    protected final ISVAuthService authService;

    protected final UCFRedisCacheFactory cacheFactory;
    protected StringKeyCache<CommonAuthResult> yhtTokenCache;
    public static final String YHT_ACCESS_TOKEN = "yht_access_token";
    public static final String USER_ID = "userId";
    public static final String TENANT_ID = "tenantId";

    @PostConstruct
    public void init() {
        yhtTokenCache = cacheFactory
                .buildStringKeyCache("yhtTokenCache", 1000, 20000, Duration.ofMinutes(60), true);
    }

//    protected void buildContextByCookie(Cookie[] cookies) {
//        String tenantId = null;
//        String userId = null;
//        String yhtAccessToken = null;
//        for (Cookie cookie : cookies) {
//            if (TENANT_ID.equals(cookie.getName())) {
//                tenantId = cookie.getValue();
//            }
//            if (USER_ID.equals(cookie.getName())) {
//                userId = cookie.getValue();
//            }
//            if (YHT_ACCESS_TOKEN.equals(cookie.getName())) {
//                yhtAccessToken = cookie.getValue();
//            }
//        }
//        CommonAuthResult authResult =new CommonAuthResult(tenantId,userId);
//        buildAppContext(authResult, yhtAccessToken, "");
//        buildMddBaseContext(authResult, yhtAccessToken);
//    }

    public boolean buildContextByYhtAccessToken(String yhtAccessToken, String serviceCode) {
        CommonAuthResult authResult = yhtTokenCache.getV(yhtAccessToken);
        if (null == authResult) {
            log.info("redis里面通过token没有获取到租户信息");
            // 根据yhtAccessToken获取用户信息（tenantId，UserId）
            Map<String, Object> authMap = authApi.authUserByYhtAccessToken(yhtAccessToken);
            if (authMap == null) {
                log.info("根据yhtAccessToken {} 获取用户信息失败", yhtAccessToken);
                return false;
            }
            JSONObject userObject = (JSONObject) authMap.get("user");
            JSONObject tenantObject = (JSONObject) authMap.get("tenant");
            //使用authMap构建CommonAuthResult
            authResult = new CommonAuthResult();
            authResult.setYht_isAdmin(tenantObject.getBoolean("yht_isAdmin"));
            authResult.setYhtUserId(userObject.getString("userId"));
            authResult.setYhtTenantId(tenantObject.getString("tenantId"));
            authResult.setDefaultOrg(tenantObject.getString("defaultOrg"));
            authResult.setNewArch(tenantObject.getBoolean("newArch"));
            JSONArray identities = (JSONArray) tenantObject.get("identities");
            if(identities != null && identities.size() > 0) {
                JSONObject identity = (JSONObject) identities.get(0);
                authResult.setUserId(Long.parseLong(identity.getString("id")));
                authResult.setTenantId(identity.getString("yxyTenantId"));
            }

            log.info("根据yhtAccessToken {} 获取用户信息成功，tenantId {} ，userId {}", yhtAccessToken, authResult.getTenantId(), authResult.getYhtUserId());
            yhtTokenCache.putVK(authResult, yhtAccessToken);
        }
        buildContext(authResult, yhtAccessToken, serviceCode);
        return true;
    }

    public static void buildContext(CommonAuthResult authResult, String yhtAccessToken, String serviceCode) {
        buildAppContext(authResult, yhtAccessToken, serviceCode);
        buildMddBaseContext(authResult, yhtAccessToken);
        buildInvocationInfoProxy(authResult, yhtAccessToken);
    }

    */
/**
     * 添加AppContex的用户上下文（InheritableThreadLocal线程变量，从主线程创建子线程会传递信息）
     *//*

    private static void buildAppContext(CommonAuthResult authResult, String yhtAccessToken, String serviceCode) {
        LoginUser user = buildUser(authResult, yhtAccessToken);
        try {
            AppContext.setToken(yhtAccessToken);
            AppContext.setThreadContext(MddConstants.PARAM_SERVICE_CODE, serviceCode);
            AppContext.setCurrentUser(yhtAccessToken, user);
        } catch (Exception e) {
            log.warn("{} when update app context current user {}", e.getClass().getSimpleName(),
                    e.getMessage());
        }
    }

    private static LoginUser buildUser(CommonAuthResult authResult, String yhtAccessToken) {
        LoginUser user = new LoginUser();
        user.setYhtTenantId(authResult.getTenantId());
        user.setTenant(authResult.getTenantId());
        user.setYhtUserId(authResult.getYhtUserId());
        user.setYhtAccessToken(yhtAccessToken);
        user.setLoginUserToken(yhtAccessToken);
        user.set("yht_isAdmin",authResult.getYht_isAdmin());
        if (StringUtils.isNotEmpty(authResult.getDefaultOrg())) {
            user.put("defaultOrg", authResult.getDefaultOrg());
        }
        user.put("newArch", authResult.isNewArch());
        user.setId(authResult.getUserId());
        return user;
    }

    */
/**
     * 设置MddBaseContext用户的上下文信息（InheritableThreadLocal线程变量，从主线程创建子线程会传递信息）
     *//*

    private static void buildMddBaseContext(CommonAuthResult authResult, String yhtAccessToken) {
        LoginUser user = new LoginUser();
        user.setTenant(authResult.getTenantId());
        user.setYhtTenantId(authResult.getTenantId());
        user.setYhtUserId(authResult.getYhtUserId());
        user.setId(authResult.getUserId());
        if (StringUtils.isNotEmpty(authResult.getDefaultOrg())) {
            user.put("defaultOrg", authResult.getDefaultOrg());
        }
        user.put("newArch", authResult.isNewArch());
        user.set("yht_isAdmin",authResult.getYht_isAdmin());
        AppContext.setCurrentUser(user);
        AppContext.setTenantId(authResult.getTenantId());
        AppContext.setUserId(authResult.getYhtUserId());
        AppContext.setThreadContext("yhtTenantId", authResult.getTenantId());
        AppContext.setToken(yhtAccessToken);
        AppContext.setThreadContext(POIConstant.IMPORT_MULLANG_CODES,
                LanguageVO.DEFAULT_LIST.get("diwork"));
    }

    */
/**
     * 设置RPC远程方法调用的时候，将调用方的上下文的信息携带到服务提供方
     *//*

    private static void buildInvocationInfoProxy(CommonAuthResult authResult, String yhtAccessToken) {
        InvocationInfoProxy.setUserid(authResult.getYhtUserId());
        InvocationInfoProxy.setTenantid(authResult.getTenantId());
        InvocationInfoProxy.setToken(yhtAccessToken);
        InvocationInfoProxy.setExtendAttribute(YHT_ACCESS_TOKEN, yhtAccessToken);
    }

    */
/**
     * 清理线程变量
     *//*

    public static void clearContext() {
        InvocationInfoProxy.reset();
        try {
            AppContext.clear();
        } catch (Exception e) {
            // for code as shit
            log.debug("exception when clear app context");
        }
    }
}*/
